package com.glela.goods.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glela.common.constant.BaseConstants;
import com.glela.common.model.ProductTag;
import com.glela.goods.dao.vo.LimitSaleGoodsInventroy;
import com.glela.goods.mapper.LimitTimeSaleDetailMapper;
import com.glela.goods.mapper.LimitTimeSaleMapper;
import com.glela.goods.model.GoodsNavigate;
import com.glela.goods.model.GoodsPrice;
import com.glela.goods.model.LimitTimeSale;
import com.glela.goods.model.StoreGoods;
import com.glela.goods.model.po.LimitTimeSaleTitlePo;
import com.glela.goods.model.request.RequestLimitSaleGoodsListModel;
import com.glela.goods.model.response.RespLimitSaleTomorrow;
import com.glela.goods.model.response.ResponseLimitSaleGoods;
import com.glela.goods.model.response.ResponseLimitSaleTitle;
import com.glela.goods.model.vo.limitsale.GoodsPriceVo;
import com.glela.goods.model.vo.limitsale.LimitSaleGoodsVo;
import com.glela.goods.model.vo.limitsale.LimitSaleTitleVo;
import com.glela.goods.model.vo.limitsale.LimitSaleTomorrowTitleVo;
import com.glela.goods.service.GoodsNavigateService;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.InventoryService;
import com.glela.goods.service.LimitTimeSaleService;
import com.glela.goods.service.StoreGoodsService;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.UserService;

@Service
public class LimitTimeSaleServiceImpl implements LimitTimeSaleService {
	private static Logger					logger				= LoggerFactory.getLogger(LimitTimeSaleServiceImpl.class);
	private static final DateTimeFormatter	DATE_TIME_FORMATTER	= DateTimeFormat.forPattern(BaseConstants.DATE_FORMAT);
	@Autowired
	private LimitTimeSaleMapper				limitTimeSaleMapper;
	@Autowired
	private LimitTimeSaleDetailMapper		limitTimeSaleDetailMapper;
	@Autowired
	private UserService						userService;
	@Autowired
	private InventoryService				inventoryService;
	@Autowired
	private GoodsService					goodsService;
	@Autowired
	private GoodsNavigateService			goodsNavigateService;
	@Autowired
	private StoreGoodsService				storeGoodsService;

	@Override
	public ResponseLimitSaleTitle findLimitSaleTitle(DateTime nowDate) {
		ResponseLimitSaleTitle responseLimitSaleTitle = new ResponseLimitSaleTitle();
		responseLimitSaleTitle.setTitles(new LinkedList<LimitSaleTitleVo>());
		if (nowDate == null) {
			nowDate = DateTime.now();
		}
		DateTime yesterday = nowDate.minusDays(1);
		DateTime yesterDay = new DateTime(yesterday.getYear(), yesterday.getMonthOfYear(), yesterday.getDayOfMonth(), 21, 0, 0);
		//		String yesterdayStr = yesterDay.toString(BaseConstants.DATE_FORMAT);
		//昨日竞选
		boolean hasYesterday = false;
		int yesterdayNum = limitTimeSaleMapper.hasYesterdaysPick(yesterDay.toDate(), nowDate.toDate());
		if (yesterdayNum > 0) {
			LimitSaleTitleVo limitSaleTitleVo = new LimitSaleTitleVo();
			limitSaleTitleVo.setLimitTimeSaleId(0);
			limitSaleTitleVo.setTitle("昨日精选");
			limitSaleTitleVo.setSubtitle("别错过");
			limitSaleTitleVo.setStatus(1);
			responseLimitSaleTitle.getTitles().add(limitSaleTitleVo);
			hasYesterday = true;
		}

		//		int nowBeginDate = NumberUtils.toInt(nowDate.toString(BaseConstants.DATE_FORMAT_YYYYMMDDHH));
		long nowBeginDate = nowDate.getMillis();
		DateTime _tomorrow = new DateTime(nowDate.getYear(), nowDate.getMonthOfYear(), nowDate.getDayOfMonth(), 0, 0).plusDays(1);
		//当日热卖
		//		String _tomorrow_date = _tomorrow.toString(BaseConstants.DATE_FORMAT);
		List<LimitTimeSale> limitTimeSales = limitTimeSaleMapper.todayLimitSaleTitle(yesterDay.toDate(), _tomorrow.toDate(), nowDate.toDate());
		long lowTime = 0;
		int i = 0;
		int isNowIndex = 0;
		boolean hasDefaltOption = false;
		for (LimitTimeSale limitTimeSale : limitTimeSales) {
			if (limitTimeSale.getSkuCount() <= 0) {
				continue;
			}
			LimitSaleTitleVo limitSaleTitleVo = new LimitSaleTitleVo();
			limitSaleTitleVo.setStartTime(limitTimeSale.getFullBeginTime());
			DateTime dateTime = new DateTime(limitTimeSale.getFullBeginTime());

			limitSaleTitleVo.setLimitTimeSaleId(limitTimeSale.getId());
			//			limitSaleTitleVo.setTitle((limitTimeSale.getBeginHour() < 10 ? "0" : "") + limitTimeSale.getBeginHour() + ":00");
			limitSaleTitleVo.setTitle(dateTime.toString("HH:mm"));
			if (!hasDefaltOption) {
				//				int now_beginTime = limitTimeSale.getBeginDate() * 100 + limitTimeSale.getBeginHour();
				long now_beginTime = dateTime.getMillis();
				if (now_beginTime <= nowBeginDate) {
					if (now_beginTime > lowTime) {
						lowTime = now_beginTime;
						isNowIndex = i;
					}
					limitSaleTitleVo.setSubtitle("进行中");
					limitSaleTitleVo.setStatus(2);
				} else {
					hasDefaltOption = true;
					limitSaleTitleVo.setSubtitle("预热中");
					limitSaleTitleVo.setStatus(3);
				}

			} else {
				limitSaleTitleVo.setSubtitle("预热中");
				limitSaleTitleVo.setStatus(3);
			}
			responseLimitSaleTitle.getTitles().add(limitSaleTitleVo);
			i++;
		}
		if (hasYesterday && i > 0) {
			isNowIndex += 1;
		}
		responseLimitSaleTitle.setShowDefIndex(isNowIndex);
		//明日预告
		int tomorrowNum = limitTimeSaleMapper.hasTomorrowTrailer(_tomorrow.toDate(), _tomorrow.plusDays(1).toDate());
		if (tomorrowNum > 0) {
			LimitSaleTitleVo limitSaleTitleVo = new LimitSaleTitleVo();
			limitSaleTitleVo.setLimitTimeSaleId(0);
			limitSaleTitleVo.setTitle("明日预告");
			limitSaleTitleVo.setSubtitle("抢先看");
			limitSaleTitleVo.setStatus(4);
			responseLimitSaleTitle.getTitles().add(limitSaleTitleVo);
		}
		if (CollectionUtils.isEmpty(responseLimitSaleTitle.getTitles())) {
			LimitSaleTitleVo limitSaleTitleVo = new LimitSaleTitleVo();
			limitSaleTitleVo.setLimitTimeSaleId(0);
			limitSaleTitleVo.setTitle("暂无抢购");
			limitSaleTitleVo.setSubtitle("敬请期待");
			limitSaleTitleVo.setStatus(1);
			responseLimitSaleTitle.getTitles().add(limitSaleTitleVo);
		}
		return responseLimitSaleTitle;
	}

	@Override
	public ResponseLimitSaleGoods findLimitSaleGoodsList(RequestLimitSaleGoodsListModel requestLimitSaleGoodsListModel, ResponseUser _login_user, DateTime nowDate) {
		ResponseLimitSaleGoods returnGoods = new ResponseLimitSaleGoods();
		if (nowDate == null) {
			nowDate = DateTime.now();
		}
		//当天整点
		DateTime nowDay = new DateTime(nowDate.getYear(), nowDate.getMonthOfYear(), nowDate.getDayOfMonth(), 0, 0);

		//		String yesterdayStr = new DateTime(yesterDay.getYear(), yesterDay.getMonthOfYear(), yesterDay.getDayOfMonth(), 21, 0, 0).toString(BaseConstants.DATE_FORMAT);
		switch (requestLimitSaleGoodsListModel.getStatus()) {
			case 1://分时抢购
				DateTime yesterDay = nowDay.minusDays(1);

				PageHelper.startPage(requestLimitSaleGoodsListModel.getPageNum(), requestLimitSaleGoodsListModel.getPageSize());
				Page<LimitSaleGoodsVo> yesterdayDetail = limitTimeSaleDetailMapper.yesterdaysPick(new DateTime(yesterDay.getYear(), yesterDay.getMonthOfYear(), yesterDay.getDayOfMonth(), 21, 0, 0).toDate(), nowDate.toDate());
				_pack_limit_sale_goods(returnGoods, _login_user, yesterdayDetail, requestLimitSaleGoodsListModel.getStatus());
				break;
			case 3://当日特卖-预热中
				requestLimitSaleGoodsListModel.setPageSize(50);
			case 2://当日特卖-进行中
				PageHelper.startPage(requestLimitSaleGoodsListModel.getPageNum(), requestLimitSaleGoodsListModel.getPageSize());
				Page<LimitSaleGoodsVo> limitTimeSaleDetails = limitTimeSaleDetailMapper.selectGoodsByLimitTimeSaleId(requestLimitSaleGoodsListModel.getLimitTimeSaleId(), nowDate.toDate());
				_pack_limit_sale_goods(returnGoods, _login_user, limitTimeSaleDetails, requestLimitSaleGoodsListModel.getStatus());
				break;
			case 4://明日预告
				if (_login_user != null && _login_user.isStoreLevel()) {
					_pack_limit_sale_goods(returnGoods, _login_user, new Page<LimitSaleGoodsVo>(), requestLimitSaleGoodsListModel.getStatus());
				} else {
					DateTime _tomorrow = nowDay.plusDays(1);
					PageHelper.startPage(requestLimitSaleGoodsListModel.getPageNum(), requestLimitSaleGoodsListModel.getPageSize());
					Page<LimitSaleGoodsVo> goodsVos = limitTimeSaleDetailMapper.tomorrowTrailer(_tomorrow.toDate(), _tomorrow.plusDays(1).toDate(), nowDate.toDate());
					_pack_limit_sale_goods(returnGoods, _login_user, goodsVos, requestLimitSaleGoodsListModel.getStatus());
				}
				break;

			default:
				break;
		}
		return returnGoods;
	}

	private void _pack_limit_sale_goods(ResponseLimitSaleGoods returnGoods, ResponseUser _login_user, Page<LimitSaleGoodsVo> yesterdayDetail, int status) {
		_pack_limit_sale_goods_vo(_login_user, yesterdayDetail, status);
		PageInfo<LimitSaleGoodsVo> pageInfo = yesterdayDetail.toPageInfo();
		returnGoods.setHasNextPage(pageInfo.isHasNextPage());
		returnGoods.setPageNum(pageInfo.getPageNum());
		returnGoods.setPageSize(pageInfo.getPageSize());
		returnGoods.setGoodsList(yesterdayDetail);
		returnGoods.setSize(yesterdayDetail.size());
		returnGoods.setTotal(yesterdayDetail.getTotal());
	}

	private void _pack_limit_sale_goods_vo(ResponseUser _login_user, List<LimitSaleGoodsVo> yesterdayDetail, int status) {
		if (CollectionUtils.isEmpty(yesterdayDetail)) {
			return;
		}
		long _store_user_id = -1;
		User _store_user = null;
		if (_login_user == null || _login_user.getUserId() == null) {
			_store_user_id = BaseConstants.XZ_SISTER;
		} else {
			_store_user = userService.selectRecommendFromByUserId(_login_user.getUserId());
			if (_store_user == null) {
				_store_user_id = BaseConstants.XZ_SISTER;
			} else {
				_store_user_id = _store_user.getId();
			}
		}
		if (_store_user == null) {
			_store_user = userService.getUser(_store_user_id);
		}

		Set<Long> goodsIdSet = new HashSet<Long>();//商品id集合
		Map<Integer, Set<Long>> limitSaleGoodsIdMap = new HashMap<>();//分时抢购商品集合
		for (LimitSaleGoodsVo limitSaleGoodsVo : yesterdayDetail) {
			goodsIdSet.add(limitSaleGoodsVo.getGoodsId());
			if (limitSaleGoodsIdMap.get(limitSaleGoodsVo.getLimitTimeSaleId()) == null) {
				limitSaleGoodsIdMap.put(limitSaleGoodsVo.getLimitTimeSaleId(), new HashSet<Long>());
			}
			limitSaleGoodsIdMap.get(limitSaleGoodsVo.getLimitTimeSaleId()).add(limitSaleGoodsVo.getGoodsId());
		}
		/*批量查询商品相关信息*/
		//库存
		LimitSaleGoodsInventroy limitSaleGoodsInventroy = inventoryService.findDynaByGoodsId(limitSaleGoodsIdMap);
		//图片
		Map<Long, List<GoodsNavigate>> goodsNavigateMap = goodsNavigateService.queryByGoodsIds(goodsIdSet);

		//价格
		Map<String, GoodsPrice> goodsProdicMap = new HashMap<>();
		for (Integer limitTimeSaleId : limitSaleGoodsIdMap.keySet()) {
			try {
				Map<Long, GoodsPrice> gos = goodsService.getGoodsViewPriceForGoodsLimitTimeSale(_store_user, limitTimeSaleId, limitSaleGoodsIdMap.get(limitTimeSaleId));
				for (Long goodsId : gos.keySet()) {
					if (goodsId == null) {
						continue;
					}
					goodsProdicMap.put(gos.get(goodsId).getLimitTimeSaleId() + "_" + goodsId, gos.get(goodsId));
				}
			} catch (Exception e) {
				logger.error("获取分时抢购商品价格信息失败：{}-{}:{}", limitTimeSaleId, limitSaleGoodsIdMap.get(limitTimeSaleId), e.getMessage(), e);
			}
		}
		//是否上架
		Map<Long, StoreGoods> goodsIdStoreGoodsMap = null;
		if (_login_user != null && _login_user.isStoreLevel()) {
			goodsIdStoreGoodsMap = storeGoodsService.queryStoreGoods(_login_user.getUserId(), goodsIdSet);
		}
		boolean is_Preheat = status == 3;//是预热
		List<LimitSaleGoodsVo> _avl_list = new LinkedList<>();//可用商品
		for (LimitSaleGoodsVo limitSaleGoodsVo : yesterdayDetail) {
			//库存
			//			limitSaleGoodsVo.setInventoryNum(inventoryService.findDynaByGoodsId(limitSaleGoodsVo.getGoodsId(), limitSaleGoodsVo.getLimitTimeSaleId()));
			limitSaleGoodsVo.setInventoryNum(limitSaleGoodsInventroy.getNums(limitSaleGoodsVo.getLimitTimeSaleId(), limitSaleGoodsVo.getGoodsId()));

			if (is_Preheat && limitSaleGoodsVo.getInventoryNum() < 1) {
				continue;
			}

			if (limitSaleGoodsVo.getSalerNums() < 0) {
				limitSaleGoodsVo.setSalerNums(0);
			}
			limitSaleGoodsVo.setGoodsPrice(new GoodsPriceVo());
			//价格
			GoodsPrice _goods_price = goodsProdicMap.get(limitSaleGoodsVo.getLimitTimeSaleId() + "_" + limitSaleGoodsVo.getGoodsId());
			if (_goods_price == null) {
				logger.error("分时抢购{}商品{}获取价格为空", limitSaleGoodsVo.getLimitTimeSaleId(), limitSaleGoodsVo.getGoodsId());
			} else {
				limitSaleGoodsVo.getGoodsPrice().setCommission(_goods_price.getCommission());
				limitSaleGoodsVo.getGoodsPrice().setMarketPirce(_goods_price.getMarketPirce());
				limitSaleGoodsVo.getGoodsPrice().setSalePrice(_goods_price.getSalePrice());
				limitSaleGoodsVo.getGoodsPrice().setXzb(_goods_price.getXzb());
				limitSaleGoodsVo.getGoodsPrice().setProductId(_goods_price.getProductId());
			}

			//热卖标签
			if (status == 2) {
				limitSaleGoodsVo.setProductTags(new LinkedList<ProductTag>());
				limitSaleGoodsVo.getProductTags().add(new ProductTag());
			}
			//图片
			if (goodsNavigateMap.get(limitSaleGoodsVo.getGoodsId()) != null && CollectionUtils.isNotEmpty(goodsNavigateMap.get(limitSaleGoodsVo.getGoodsId()))) {
				limitSaleGoodsVo.getGoodsNavigates().add(goodsNavigateMap.get(limitSaleGoodsVo.getGoodsId()).get(0));
			}
			//是否上架
			if (_login_user != null && _login_user.isStoreLevel()) {//店主级别显示是否上下家
				//				StoreGoods storeGoods = storeGoodsMapper.selectUserStoreGoods(_store_user_id, limitSaleGoodsVo.getGoodsId());
				limitSaleGoodsVo.setOnSale(MapUtils.getObject(goodsIdStoreGoodsMap, limitSaleGoodsVo.getGoodsId(), null) != null);
			} else {
				limitSaleGoodsVo.setOnSale(false);
			}
			if (is_Preheat) {
				//设置可用
				_avl_list.add(limitSaleGoodsVo);
			}
		}
		if (is_Preheat) {
			yesterdayDetail.clear();
			yesterdayDetail.addAll(_avl_list);
		}
		_avl_list = null;
	}

	@Override
	public long findTomorrowTrailerGoodsNums() {
		DateTime nowDate = new DateTime();
		DateTime _tomorrow = new DateTime(nowDate.getYear(), nowDate.getMonthOfYear(), nowDate.getDayOfMonth(), 0, 0).plusDays(1);
		Long selectTomorrowTrailerGoodsNums = this.limitTimeSaleDetailMapper.selectTomorrowTrailerGoodsNums(_tomorrow.toDate(), _tomorrow.plusDays(1).toDate(), nowDate.toDate());
		return selectTomorrowTrailerGoodsNums == null || selectTomorrowTrailerGoodsNums < 0 ? 0 : selectTomorrowTrailerGoodsNums;
	}

	@Override
	public RespLimitSaleTomorrow getTomorrowTrailer(RequestLimitSaleGoodsListModel requestLimitSaleGoodsListModel) {
		ResponseUser _login_user = this.userService.selectUserRoleById(requestLimitSaleGoodsListModel.getUserId());
		RespLimitSaleTomorrow returnTomorrow = new RespLimitSaleTomorrow();
		returnTomorrow.setTomorrowTrailerTitles(new LinkedList<LimitSaleTomorrowTitleVo>());

		//校验有效性
		DateTime nowDate = new DateTime();
		DateTime _tomorrow = new DateTime(nowDate.getYear(), nowDate.getMonthOfYear(), nowDate.getDayOfMonth(), 0, 0).plusDays(1);
		DateTime _after_tomorrow_time = _tomorrow.plusDays(1);
		DateTime _start_date = null;
		if (StringUtils.isBlank(requestLimitSaleGoodsListModel.getStartTime())) {
			_start_date = _tomorrow.minusMillis(1);
		} else {
			_start_date = DateTime.parse(requestLimitSaleGoodsListModel.getStartTime(), DATE_TIME_FORMATTER);
		}
		if (_start_date == null || _start_date.getMillis() < _tomorrow.getMillis()) {
			_start_date = _tomorrow.minusMillis(1);
		} else {
			if (_start_date.getMillis() > _after_tomorrow_time.getMillis()) {
				return returnTomorrow;
			}
		}
		//查询预告分时头信息
		List<LimitTimeSaleTitlePo> saleTitleVos = this.limitTimeSaleDetailMapper.selectTomorrowTrailerTitle(_start_date.toString(BaseConstants.DATE_FORMAT), _after_tomorrow_time.toString(BaseConstants.DATE_FORMAT));
		int i = 0;
		int _total_size = 0;
		for (LimitTimeSaleTitlePo limitTimeSaleTitlePo : saleTitleVos) {
			if (_total_size >= requestLimitSaleGoodsListModel.getPageSize()) {
				break;
			}
			LimitSaleTomorrowTitleVo addTomorrowTitle = new LimitSaleTomorrowTitleVo();
			returnTomorrow.getTomorrowTrailerTitles().add(addTomorrowTitle);

			addTomorrowTitle.setLimitTimeSaleId(limitTimeSaleTitlePo.getLimitTimeSaleId());
			addTomorrowTitle.setGoodsNums(limitTimeSaleTitlePo.getGoodsNums());
			addTomorrowTitle.setFullBeginTime(limitTimeSaleTitlePo.getFullBeginTime());
			//			addTomorrowTitle.setProductNums(limitTimeSaleTitlePo.getProductNums());
			DateTime _full_begin_time = DateTime.parse(limitTimeSaleTitlePo.getFullBeginTime(), DATE_TIME_FORMATTER);
			//			addTomorrowTitle.setTitle((limitTimeSaleTitlePo.getBeginHour() < 10 ? "0" : "") + limitTimeSaleTitlePo.getBeginHour() + ":00");
			addTomorrowTitle.setTitle(_full_begin_time.toString(BaseConstants.DATE_FORMAT_MMddHHmm));
			//查询此时段分时抢购商品
			Page<LimitSaleGoodsVo> selectGoodsByLimitTimeSaleId = this.limitTimeSaleDetailMapper.selectGoodsByLimitTimeSaleId(limitTimeSaleTitlePo.getLimitTimeSaleId(), nowDate.toDate());
			addTomorrowTitle.setProducts(selectGoodsByLimitTimeSaleId);
			_pack_limit_sale_goods_vo(_login_user, selectGoodsByLimitTimeSaleId, 4);
			_total_size += selectGoodsByLimitTimeSaleId.size();
			i++;
		}
		returnTomorrow.setHasNextPage(saleTitleVos.size() > i);
		return returnTomorrow;
	}

}
